package com.jie.other.aidl

import android.app.ActivityManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.IBinder
import android.os.Process
import android.os.RemoteCallbackList
import android.os.RemoteException
import android.util.Log
import com.blankj.utilcode.util.LogUtils
import java.util.concurrent.CopyOnWriteArrayList

/**
 * 远程服务（设置在另一个进程，用于模拟跨进程通讯）
 */
class PersonService : Service() {

    // 数据集合，确保线程安全
    private val mList = CopyOnWriteArrayList<Person>()
    // 数据改变回调集合
    private val mChangeListenerList = RemoteCallbackList<IPersonChangeListener>()
    private val mBinder: IBinder = object : IPersonManager.Stub() {
        override fun getPersonList(): MutableList<Person> {
            return mList
        }

        override fun registerChangeListener(listener: IPersonChangeListener?) {
            mChangeListenerList.register(listener)
        }

        override fun unregisterChangeListener(listener: IPersonChangeListener?) {
            mChangeListenerList.unregister(listener)
        }

        override fun addPersonIn(person: Person?) {
            person?.let {
                it.name += "_in"
                mList.add(it)
                onDataChange(it)
            }
        }

        override fun addPersonOut(person: Person?) {
            person?.let {
                it.name += "_out"
                mList.add(it)
                onDataChange(it)
            }
        }

        override fun addPersonInOut(person: Person?) {
            person?.let {
                it.name += "_inout"
                mList.add(it)
                onDataChange(it)
            }
        }

        override fun delayAddPerson(person: Person?) {
            person?.let {
                Thread.sleep(2000)
                it.name += "_delay"
                mList.add(it)
                onDataChange(it)
            }
        }

        override fun clearPerson() {
            mList.clear()
            onDataChange(null)
        }

        override fun killProcess() {
            try {
                //注意：不能先杀掉主进程，否则逻辑代码无法继续执行，需先杀掉相关进程最后杀掉主进程
                val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
                activityManager.runningAppProcesses.forEach {
                    Log.i("process","${it.pid}+${it.processName}+${Process.myPid()}")
                }
                Process.killProcess(Process.myPid())
            }catch (e: Exception){
                e.printStackTrace()
            }
        }

        fun onDataChange(person: Person?){
            val count = mChangeListenerList.beginBroadcast()
            for (i in 0 until  count){
                try {
                    mChangeListenerList.getBroadcastItem(i).onDataChange(person)
                } catch (e: RemoteException){
                    e.printStackTrace()
                }
            }
            mChangeListenerList.finishBroadcast()
        }

    }

    override fun onBind(intent: Intent): IBinder? {
        if (checkCallingOrSelfPermission(AIDLConstant.PERSON_SERVICE_PERMISSION) ==
            PackageManager.PERMISSION_DENIED
        ) {
            LogUtils.e("没有权限绑定远程服务")
            return null
        }
        return mBinder
    }

    override fun onCreate() {
        super.onCreate()
        mList.add(Person(age = 11, name = "张三"))
        mList.add(Person(age = 15, name = "李四"))
    }
}